package com.feng.gulimall.product.service.impl;

import com.alibaba.nacos.shaded.io.grpc.netty.shaded.io.netty.util.internal.StringUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feng.common.constant.ProductConstant;
import com.feng.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.feng.gulimall.product.entity.AttrGroupEntity;
import com.feng.gulimall.product.entity.CategoryEntity;
import com.feng.gulimall.product.service.AttrAttrgroupRelationService;
import com.feng.gulimall.product.service.AttrGroupService;
import com.feng.gulimall.product.service.CategoryService;
import com.feng.gulimall.product.vo.AttrRespVo;
import com.feng.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.feng.common.utils.PageUtils;
import com.feng.common.utils.Query;

import com.feng.gulimall.product.dao.AttrDao;
import com.feng.gulimall.product.entity.AttrEntity;
import com.feng.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;

import javax.security.auth.callback.LanguageCallback;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String type) {
        // 搜索条件
        String key = (String) params.get("key");
        IPage<AttrEntity> page;
        // catelogId默认为零,查询所有
        if (catelogId == 0){
            LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();
            page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryLike(wrapper, key, type)
            );
        }else {
            // select * from pms_attr_group where catelog_id = 1 and (attr_group_id = 1 or attr_group_name like %%) order by sort
            LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AttrEntity::getCatelogId, catelogId);
            page = this.page(
                    new Query<AttrEntity>().getPage(params),
                    queryLike(wrapper, key, type)
            );
        }
        PageUtils pageUtils = new PageUtils(page);
        // 处理查询结果，更改为 AttrRespVo 返回
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> attrRespVos = records.stream().map((attrEntity) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            // 先将已经存在的数据copy过来
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            // 再设置其他属性
            CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrRespVo.setCatelogName(categoryEntity.getName());
            }
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId());
            AttrAttrgroupRelationEntity one = attrAttrgroupRelationService.getOne(wrapper);
            if (one != null && one.getAttrGroupId() != null) {
                AttrGroupEntity groupEntity = attrGroupService.getById(one.getAttrGroupId());
                attrRespVo.setGroupName(groupEntity.getAttrGroupName());
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        // 更换结果集
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    @Transactional
    public void saveDetial(AttrVo attrVo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        // 插入基本信息
        baseMapper.insert(attrEntity);
        // 插入关联信息
        // 如果是基本属性，才添加关联关系
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }
    }

    @Override
    public AttrRespVo getAttrInfo(Long attrId) {
        AttrRespVo attrRespVo = new AttrRespVo();
        // 查出当前的基本信息
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        // 封装分类信息
        if (attrRespVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()){
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId());
            AttrAttrgroupRelationEntity one = attrAttrgroupRelationService.getOne(wrapper);
            if (one != null){
                attrRespVo.setAttrGroupId(one.getAttrGroupId());
                AttrGroupEntity attrGroupEntity = attrGroupService.getById(one.getAttrGroupId());
                if (attrGroupEntity != null){
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
        }
        // 封装分组信息
        Long[] catelogIds = categoryService.getCatelogIds(attrEntity.getCatelogId());
        attrRespVo.setCatelogPath(catelogIds);
        CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
        if (categoryEntity != null){
            attrRespVo.setCatelogName(categoryEntity.getName());
        }
        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attrVo) {
        // 先更新
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        baseMapper.updateById(attrEntity);
        // 更新关联关系
        if (attrVo.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attrVo.getAttrGroupId() != null){
            LambdaQueryWrapper<AttrAttrgroupRelationEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(AttrAttrgroupRelationEntity::getAttrId, attrEntity.getAttrId());
            // 更新数据
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            // 如果没有建立关联关系
            if (attrAttrgroupRelationService.getOne(wrapper) == null && attrVo.getAttrGroupId() != null){
                attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
                attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
            }else {
                attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
                attrAttrgroupRelationService.update(attrAttrgroupRelationEntity, wrapper);
            }
        }
    }

    @Override
    @Transactional
    public void removeAttrs(Long[] attrIds) {
        // 删除当前表
        baseMapper.deleteBatchIds(Arrays.asList(attrIds));
        for (Long attrId : attrIds) {
            // 删除关联表
            attrAttrgroupRelationService.remove(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                    .eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
        }
    }

    @Override
    public List<AttrEntity> getRelationAttr(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.getBaseMapper().selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                .eq(AttrAttrgroupRelationEntity::getAttrGroupId, attrGroupId));
        List<AttrEntity> attrEntities = attrAttrgroupRelationEntities.stream().map((attrAttrgroupRelationEntity) -> {
            return baseMapper.selectById(attrAttrgroupRelationEntity.getAttrId());
        }).collect(Collectors.toList());

        return attrEntities;
    }

    @Override
    public PageUtils getAttrNoRelation(Map<String, Object> params, Long attrGroupId) {
        String key = (String) params.get("key");
        // 查出对应的分类信息
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 查出当前分类的所有信息
        List<AttrGroupEntity> attrGroupEntities = attrGroupService.getBaseMapper().selectList(new LambdaQueryWrapper<AttrGroupEntity>()
                .eq(AttrGroupEntity::getCatelogId, catelogId));
        // 取到这些信息的groupId
        List<Long> groupIds = attrGroupEntities.stream().map((attrGroup) -> {
            return attrGroup.getAttrGroupId();
        }).collect(Collectors.toList());
        // 查出已经关联了的关联信息
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntities = attrAttrgroupRelationService.getBaseMapper().selectList(new LambdaQueryWrapper<AttrAttrgroupRelationEntity>()
                .in(AttrAttrgroupRelationEntity::getAttrGroupId, groupIds));
        // 查询出这些关联信息的attrId
        List<Long> attrIds = attrAttrgroupRelationEntities.stream().map((attrAttrgroupRelationEntity) -> {
            return attrAttrgroupRelationEntity.getAttrId();
        }).collect(Collectors.toList());

        // 再查出对应的属性信息
        // 封装查询条件
        LambdaQueryWrapper<AttrEntity> wrapper = new LambdaQueryWrapper<AttrEntity>()
                .eq(AttrEntity::getCatelogId, catelogId).notIn(attrIds != null && attrIds.size() != 0, AttrEntity::getAttrId, attrIds);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryLike(wrapper, key, "base")
        );

        List<AttrEntity> attrEntities = baseMapper.selectList(wrapper);

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(attrEntities);
        return pageUtils;
    }

    private LambdaQueryWrapper<AttrEntity> queryLike(LambdaQueryWrapper<AttrEntity> wrapper, String key, String type){
        if (key != null && !key.equals("")){
            wrapper.and((obj) -> {
                obj.eq(AttrEntity::getAttrId, key).or()
                        .like(AttrEntity::getAttrName, key);
            });
        }
        // 如果是销售属性
        if (type.equalsIgnoreCase("sale")){
            wrapper.eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        }else {
            wrapper.eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        }
        return wrapper;
    }

}
